<template>
  <el-drawer
    :visible.sync="dialogVisible"
    :title="title"
    size="65%"
    direction="rtl"
    :close-on-press-escape="true"
    :close-on-click-modal="false"
    :modal="true"
    :modal-append-to-body="true"
    custom-class="sop-drawer"
    @close="handleClose"
  >
    <div v-loading="loading" class="sop-editor-container">
      <div class="state-info">
        <i class="el-icon-s-flag" />
        <span>{{ stateName || '未知状态' }} - SOP任务目标配置</span>
      </div>

      <el-tabs v-model="activeTab" class="sop-tabs">
        <el-tab-pane label="目标" name="target">
          <div class="editor-container">
            <p class="editor-tip">描述该状态下需要达成的具体目标</p>
            <tiptap-editor
              v-model="sopData.target"
              :height="400"
              placeholder="请输入该状态的工作目标..."
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="学习资料" name="learning_materials">
          <div class="editor-container">
            <p class="editor-tip">列出完成该状态所需的学习资料和参考文档</p>
            <tiptap-editor
              v-model="sopData.learning_materials"
              :height="400"
              placeholder="请输入相关的学习资料..."
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="关键结果" name="key_results">
          <div class="editor-container">
            <p class="editor-tip">描述该状态的关键成果和衡量标准</p>
            <tiptap-editor
              v-model="sopData.key_results"
              :height="400"
              placeholder="请输入关键结果指标..."
            />
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-row :gutter="20" class="settings-row">
        <el-col :span="12">
          <el-form-item label="预计耗时(小时)">
            <el-input-number
              v-model="sopData.estimated_duration"
              :min="0"
              :max="999"
              size="small"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用">
            <el-switch
              v-model="sopData.is_active"
              active-text="启用"
              inactive-text="禁用"
              size="small"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </div>

    <div class="drawer-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
    </div>
  </el-drawer>
</template>

<script>
import TiptapEditor from '@/components/Tiptap'
import { Get as GetSOP, Post as PostSOP, Put as PutSOP } from '@/api/crm/crmorderstatesop'
import qs from 'qs'

export default {
  name: 'CrmOrderStateSOP',
  components: {
    TiptapEditor
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    stateId: {
      type: [Number, String],
      required: true
    },
    stateName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      saving: false,
      activeTab: 'target',
      sopData: {
        target: '',
        learning_materials: '',
        key_results: '',
        estimated_duration: 0,
        is_active: true
      }
    }
  },
  computed: {
    title() {
      return `设置SOP任务目标 - ${this.stateName || '未知状态'}`
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.loadSOP()
      }
    }
  },
  methods: {
    resetData() {
      this.sopData = {
        target: '',
        learning_materials: '',
        key_results: '',
        estimated_duration: 0,
        is_active: true
      }
      this.activeTab = 'target'
    },

    async loadSOP() {
      this.loading = true
      this.resetData()

      try {
        // 获取所有SOP配置，然后在前端过滤
        const response = await GetSOP(null, qs.stringify({
          pagesize: 1000
        }))

        if (response && response.success) {
          // 在前端过滤出该状态的SOP配置
          const sopRecords = response.data.data || []
          const sopRecord = sopRecords.find(item => item.crmorderstate_id === Number(this.stateId))

          if (sopRecord) {
            // 如果已有配置，加载数据
            this.sopData = {
              id: sopRecord.id,
              target: sopRecord.target || '',
              learning_materials: sopRecord.learning_materials || '',
              key_results: sopRecord.key_results || '',
              estimated_duration: sopRecord.estimated_duration || 0,
              is_active: sopRecord.is_active !== false
            }
          }
        }
      } catch (error) {
        console.error('加载SOP数据失败:', error)
        this.$message.error('加载SOP数据失败')
      }

      this.loading = false
    },

    async handleSave() {
      this.saving = true

      try {
        const data = {
          ...this.sopData,
          crmorderstate_id: this.stateId
        }

        let response
        if (this.sopData.id) {
          // 更新现有SOP
          response = await PutSOP(this.sopData.id, data)
        } else {
          // 创建新SOP
          response = await PostSOP(data)
        }

        if (response && response.success) {
          this.$message.success('SOP设置保存成功')
          this.$emit('saved')
          this.handleClose()
        } else {
          this.$message.error(response?.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存SOP失败:', error)
        this.$message.error('保存SOP失败')
      }

      this.saving = false
    },

    handleCancel() {
      this.handleClose()
    },

    handleClose() {
      this.dialogVisible = false
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
.sop-editor-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  padding: 15px 15px 75px 15px; /* 为底部按钮预留75px空间(60px按钮高度+15px间距) */
}

.state-info {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border-radius: 8px;
  margin-bottom: 15px;
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.state-info i {
  margin-right: 10px;
  font-size: 18px;
}

.sop-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.sop-tabs >>> .el-tabs__header {
  margin: 0 0 15px 0;
  background: white;
  padding: 0 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.sop-tabs >>> .el-tabs__nav-wrap {
  padding: 8px 0;
}

.sop-tabs >>> .el-tabs__item {
  font-weight: 600;
  color: #606266;
}

.sop-tabs >>> .el-tabs__item.is-active {
  color: #67c23a;
}

.sop-tabs >>> .el-tabs__active-bar {
  background-color: #67c23a;
}

.sop-tabs >>> .el-tabs__content {
  padding: 0 !important;
  flex: 1;
}

.sop-tabs >>> .el-tab-pane {
  height: 100%;
}

.editor-container {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 为编辑器底部添加渐变遮罩，提示还有更多内容 */
.editor-container::after {
  content: '';
  position: absolute;
  bottom: 15px;
  left: 15px;
  right: 15px;
  height: 30px;
  background: linear-gradient(transparent, rgba(245, 247, 250, 0.8));
  pointer-events: none;
  border-radius: 0 0 8px 8px;
}

.editor-tip {
  margin: 0 0 10px 0;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
  padding: 5px 10px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 4px;
  flex-shrink: 0;
}

/* Tiptap编辑器样式调整 */
.editor-container >>> .tiptap-editor {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.editor-container >>> .tiptap-content {
  flex: 1;
  min-height: 300px;
  overflow-y: auto;
  max-height: calc(100vh - 350px); /* 限制最大高度：100vh - (drawer标题 + state-info + tabs + settings + footer + 间距) */
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid #ebeef5;
  text-align: right;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.12);
  z-index: 1000;
  height: 60px;
  box-sizing: border-box;
}

.drawer-footer .el-button {
  min-width: 80px;
  margin-left: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}

.settings-row {
  margin-top: 15px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.settings-row .el-form-item {
  margin-bottom: 0;
}

.settings-row .el-form-item__label {
  font-size: 12px;
  color: #666;
}

/* 确保编辑器内容不被底部按钮遮挡 */
.editor-container >>> .tiptap-content {
  padding-bottom: 20px; /* 编辑器内部底部间距 */
}

/* 为编辑器添加滚动条样式 */
.editor-container >>> .tiptap-content::-webkit-scrollbar {
  width: 6px;
}

.editor-container >>> .tiptap-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.editor-container >>> .tiptap-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.editor-container >>> .tiptap-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* Drawer全局样式调整 */
</style>

<style>
/* 全局drawer样式，不加scoped */
.sop-drawer .el-drawer {
  border-radius: 10px 0 0 10px;
  overflow: hidden;
}

.sop-drawer .el-drawer__header {
  padding: 25px 20px 15px 20px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 0;
  background: linear-gradient(135deg, #f8f9fa, #fff);
}

.sop-drawer .el-drawer__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.sop-drawer .el-drawer__title::before {
  content: '⚙️';
  margin-right: 8px;
  font-size: 16px;
}

.sop-drawer .el-drawer__body {
  padding: 0;
  position: relative;
  background: #fafbfc;
}

/* 优化抽屉打开动画 */
.el-drawer__container {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}
</style>
